package demoMod.anm2editor;

import com.badlogic.gdx.Files;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import demoMod.anm2editor.core.Anm2EditorApplication;
import demoMod.anm2editor.core.MainWindow;
import demoMod.anm2editor.fonts.FontKeys;
import demoMod.anm2editor.localization.LocalizedStrings;
import demoMod.anm2editor.model.Project;
import demoMod.anm2editor.ui.QuestionBox;
import demoMod.gdxform.helpers.FontHelper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.util.PropertiesUtil;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;

public class DesktopLauncher {
    public static void main(String[] args) {
        try {
            Field environmentField = PropertiesUtil.class.getDeclaredField("environment");
            environmentField.setAccessible(true);
            Object environment = environmentField.get(PropertiesUtil.getProperties());
            Class environmentCls = Class.forName("org.apache.logging.log4j.util.PropertiesUtil$Environment");
            Field literalField = environmentCls.getDeclaredField("literal");
            literalField.setAccessible(true);
            Map<String, String> literal = (Map<String, String>) literalField.get(environment);
            literal.put("log4j2.loggerContextFactory", "org.apache.logging.log4j.core.impl.Log4jContextFactory");
        } catch (IllegalAccessException | NoSuchFieldException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
        config.backgroundFPS = 60;
        config.foregroundFPS = 60;
        config.fullscreen = false;
        config.width = 1600;
        config.height = 900;
        config.resizable = false;
        config.title = "Anm2 Editor";
        config.addIcon("icon.png", Files.FileType.Internal);

        new Anm2EditorApplication(new MainWindow(), config) {
            private boolean flag = false;

            @Override
            public void exit() {
                if (!Project.isBlankProject()) {
                    if (!flag) {
                        flag = true;
                        List<String> strings = LocalizedStrings.getStrings("ConfirmExit");
                        QuestionBox questionBox = new QuestionBox(strings.get(0), strings.get(1), FontHelper.getFont(FontKeys.SIM_HEI_14));
                        questionBox.setConfirmCallback(() -> this.postRunnable(() -> {
                            LogManager.getLogger(DesktopLauncher.class).info("Application closed.");
                            this.running = false;
                        }));
                        questionBox.setCancelCallback(() -> flag = false);
                    }
                } else {
                    super.exit();
                }
            }
        };
    }
}
